<!--手工出库物资登记-->
<template>
  <div>
    <cus-modal
      ref="modal"
      :showFullscreen="true"
      title="手工出库-添加明细"
      width="1260"
      style="height: 500px"
    >
      <cus-search>
        <cus-search-item>
          <Form
            class="materials"
            :model="form"
            ref="formValidateSearch"
            :label-width="80"
            @keydown.native.enter.prevent="onInit"
            style="margin: -24px 0 0 -20px"
          >
            <FormItem
              label="仓库"
              :label-width="45"
              class="mr_48 mb_24"
              prop="stockId"
            >
              <Select
                placeholder="全部"
                clearable
                disabled
                v-model="form.stockId"
                style="width: 200px"
              >
                <Option
                  v-for="item in storehouseTree"
                  :value="item.id"
                  :key="item.id"
                  >{{ item.name }}</Option
                >
              </Select>
            </FormItem>
            <FormItem label="物资名称" class="mr_48 mb_20" prop="productName">
              <Input
                clearable
                placeholder="请输入物资名称"
                v-model="form.productName"
                style="width: 189px"
              />
            </FormItem>
            <FormItem label="物资种类" class="mr_48 mb_20" prop="foodClassName">
              <Select
                placeholder="全部"
                clearable
                v-model="form.foodClassName"
                @on-change="postApiGoodsPoinventroyReceivepoinventroysApi()"
                style="width: 189px"
              >
                <Option
                  v-for="item in productClassTree"
                  :value="item.categoryName"
                  :key="item.categoryName"
                  >{{ item.categoryName }}</Option
                >
              </Select>
            </FormItem>
            <cusButton class="mr_20" type="primary" @onClick="search"
              >查询</cusButton
            >
            <cusButton class="mr_10" type="primary" @onClick="reset()"
              >重置</cusButton
            >
          </Form>
        </cus-search-item>
      </cus-search>
      <Table
        border
        :loading="form.loading"
        :columns="columns"
        :data="data"
        height="500"
        :size="vuex_config.tableSize"
      >
        <template slot-scope="{ row }" slot="operation">
          <div class="flex">
            <cus-button
              type="text"
              size="small"
              :style="{ color: '#1E6FFF' }"
              style="padding: 0 5px"
              @onClick="onAdd(row)"
            >
              添加
            </cus-button>
          </div>
        </template>
      </Table>
      <div class="mt_10">
        <cus-page
          :data="pages"
          class="mt_10 flex_jd"
          @pageChange="postApiGoodsPoinventroyReceivepoinventroysApi"
        ></cus-page>
      </div>
      <div slot="footer">
        <slot name="footer">
          <div class="modal-footer">
            <cus-button size="small" class="mr_2" @onClick="onCancel"
              >取消</cus-button
            >
            <cus-button type="primary" size="small" @onClick="onCancel"
              >确认</cus-button
            >
          </div>
        </slot>
      </div>
    </cus-modal>
    <!-- 添加出库量模态框 -->
    <Modal v-model="showModal" width="420" :title="showForm.productName">
      <Form
        :model="showForm"
        ref="formValidate"
        :label-width="105"
        @keydown.native.enter.prevent="onInit"
      >
        <FormItem label="计量单位:" prop="packagingUtil" class="mr_10 mb_20">
          <Select
            v-model="showForm.packagingUtil"
            @on-change="modelChange"
            disabled
            style="width: 189px"
          >
            <Option
              v-for="item in unitTree"
              :disabled="
                item.specification != modalEdit && item.specification != '公斤'
              "
              :value="item.specification"
              :key="item.specification"
            >
              {{ item.specification }}</Option
            >
          </Select>
        </FormItem>
        <FormItem
          label="单位重量(Kg):"
          prop="unitWeight"
          class="mr_24 mb_20"
        >
          <Input
            type="number"
            placeholder="请输入单位重量"
            disabled
            v-model.number="showForm.unitWeight"
            style="width: 189px"
          />
        </FormItem>
        <FormItem
          label="库存数量:"
          prop="num"
          class="mr_24 mb_20"
        >
          <Input
            type="number"
            disabled
            placeholder="请输入库存数量"
            v-model.number="showForm.packagingQty"
            style="width: 189px"
          />
        </FormItem>
        <FormItem
          label="已领用未记账数量:"
          prop="packagingRealQty"
          class="mr_24 mb_20"
        >
          <Input
            type="number"
            disabled
            placeholder="0"
            v-model.number="showForm.packagingRealQty"
            style="width: 189px"
          />
        </FormItem>
        <FormItem label="存储仓库:" class="mr_24 mb_20">
          <Select
            size="large"
            placeholder="全部"
            disabled
            v-model="showForm.stockId"
            style="width: 189px"
          >
            <Option
              v-for="item in storehouseTree"
              :value="item.id"
              :key="item.id"
              >{{ item.name }}</Option
            >
          </Select>
        </FormItem>
        <FormItem
          label="单价(元):"
          prop="packagingPrice"
          class="mr_24 mb_20"
        >
          <Input
            type="number"
            disabled
            placeholder="请输入价格"
            v-model.number="showForm.packagingPrice"
            style="width: 189px"
          />
        </FormItem>
        <FormItem
          label="出库数量:"
          prop="outWeight"
          class="mr_24 mb_20"
        >
          <InputNumber
            :placeholder="`可出库数量 (${outboundWeight})`"
            v-model="showForm.outWeight"
            :max="10000"
            :min="0"
            :precision="showForm.isWeight ? 2 : 0"
            :active-change="false"
            @input="priceInput"
            style="width: 189px"
          />
        </FormItem>
        <div
          style="
            height: 40px;
            line-height: 40px;
            color: red;
            display: flex;
            justify-content: center;
            margin-top: -25px;
            margin-left: 100px;
          "
        >
          *{{ `可出库数量 (${outboundWeight})` }}
        </div>
      </Form>
      <div slot="footer">
        <slot name="footer">
          <div class="modal-footer">
            <cus-button size="small" class="mr_2" @onClick="showModal = false"
              >取消</cus-button
            >
            <cus-button type="primary" size="small" @onClick="onOk"
              >确认</cus-button
            >
          </div>
        </slot>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  postApiGoodsPoinventroyReceivepoinventroys,

  getGoodsSelectBasSpecificationList,
  postApiGoodsOuthandaworkSave,
  postApiGoodsOutStockBillSavepooutstockbill,
  postApiGoodsOutStockBillUpdatepooutstockbill,
  updatePostOuthandawork,
  updateGoodsPoinventroyInfo,
  getBasstockList,
} from "@/api/business/manager";
import {
 
 productcategory,
} from "@/api/business/dishesModule";
const form = {
  loading: false,
  stockId: "", // 仓库id
  productName: "", // 物资名称
  foodClassName: "", // 食材种类
};
const columns = [
  {
    title: "序号",
    type: "index",
    width: 70,
    align: "center",
  },
  {
    title: "物资名称",
    key: "productName",
    minWidth: 100,
    align: "center",
  },
  {
    title: "物资种类",
    key: "goodsTypeName",
    minWidth: 100,
    align: "center",
  },
  {
    title: "计量单位",
    key: "packagingUtil",
    minWidth: 95,
    align: "center",
  },
  {
    title: "单位重量(Kg)",
    key: "unitWeight",
    minWidth: 120,
    align: "center",
  },
  {
    title: "单价(元)",
    key: "packagingPrice",
    minWidth: 90,
    align: "center",
  },
  {
    title: "是否称重出库",
    minWidth: 90,
    align: "center",
    render: (h, params) => {
      return h("span", {}, params.row.isWeight == 1 ? "是" : "否");
    },
  },
  {
    title: "入库时间",
    key: "createTime",
    minWidth: 170,
    align: "center",
  },
  {
    title: "库存数量",
    key: "packagingQty",
    minWidth: 90,
    align: "center",
  },
  {
    title: "品牌",
    key: "brand",
    minWidth: 90,
    align: "center",
  },
  {
    title: "操作",
    slot: "operation",
    minWidth: 135,
    fixed: "right",
    align: "center",
  },
];
const showForm = {
  id: "",
  productId: "", // 商品id
  poinventroyId: "", // 物资id
  goodsTypeName: "", // 类型名称
  productName: "", // 物资名称
  packagingUtil: "", // 规格specification //计量单位
  unitWeight: "", // 单位重量
  // weight: "", // 库存重量
  goodsPackagingQty: "",  //库存数量
  realQuantity: "", // 已领用未登记重量
  packagingQty: "", // 包装数量
  packagingRealQty: "", // 包装已领用数量
  outWeight: 0, // 出库重量
  recipientsWay: 0, // 领用方式
  goodsCode: "", // 商品/货物编码
  packagingPrice: "", // 价格
  num: "", // 库存重量
  stockId: "", // 仓库id
};
export default {
  components: {},
  data() {
    return {
      form: form, // 手工出库物资登记表单
      productClassTree: [], // 食材种类selectTree数据
      columns: columns, // 手工出库物资登记
      data: [], // 手工出库物资登记数据
      showModal: false, // 添加出库模态框状态
      showForm: showForm, // 添加出库量
      unitTree: [], // 规格select,tree数据
      caiGouBillNo: "", // 采购单号
      isEdit: false, // 用于判断查看详情调用修改接口使用
      flagModal: false, // 用于判断选择规格不同显示字段名称不同操作(如选择公斤,斤显示重量,选择箱,件则展示数量)
      isFlagModal: false, // 用于判断选中规格后展示重量还是数量
      modalEdit: "", // 规格名称判断入库规格,返显出库可选规格
      storehouseTree: [], // 存储仓库tree数据
      pages: {
        page: 1,
        pageSize: 10,
        pageTotal: 0,
      },
    };
  },
  computed: {
    outboundWeight() {
      let goodsPackagingQty = 0;
      goodsPackagingQty = this.showForm.packagingQty - this.showForm.packagingRealQty;
      return goodsPackagingQty.toFixed(2);
    },
  },
  props: {
    flag: {
      //flag为true查看详情录入,flag为false为手工添加
      type: Boolean,
      default: "false",
    },
  },
  mounted() {},
  methods: {
    priceInput(val) {
      let checkPlan = "" + val;
      checkPlan = checkPlan
        .replace(/[^\d.]/g, "") // 清除“数字”和“.”以外的字符
        .replace(/\.{2,}/g, ".") // 只保留第一个. 清除多余的
        .replace(/^\./g, "") // 保证第一个为数字而不是.
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");
      if (checkPlan.indexOf(".") < 0 && checkPlan !== "") {
        // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        checkPlan = parseFloat(checkPlan) + "";
      } else if (checkPlan.indexOf(".") >= 0) {
        checkPlan = checkPlan.replace(/^()*(\d+)\.(\d\d).*$/, "$1$2.$3"); // 只能输入两个小数
      }
      console.log(checkPlan);
      this.$nextTick(() => (this.showForm.outWeight = checkPlan * 1));
      return checkPlan;
    },
    show() {
      this.loading = false;
      this.$refs["modal"].show = true;
      this.productcategoryApi();
      this.getBasstockListApi();
      this.$nextTick(() => {
        this.postApiGoodsPoinventroyReceivepoinventroysApi();
      });
    },
    // 重置搜索
    reset() {
      this.$refs["formValidateSearch"].resetFields();
      this.postApiGoodsPoinventroyReceivepoinventroysApi();
    },
    // 查询
    search() {
      this.pages.page = 1;
      this.postApiGoodsPoinventroyReceivepoinventroysApi();
    },
    // 添加按钮
    onAdd(row) {
      this.showModal = true;
      this.showForm = JSON.parse(JSON.stringify(row));
      this.modalEdit = JSON.parse(JSON.stringify(row.packagingUtil));
      this.showForm.outWeight = 0;
      this.getGoodsSelectBasSpecificationListApi();
      if (row.packagingUtil == "公斤" || row.packagingUtil == "斤") {
        this.flagModal = true; // 如果规格为公斤和斤默认显示重量(公斤,斤)
        // this.isFlagModal = true; // 用于判断选中规格后展示重量还是数量
        this.showForm.recipientsWay = 0; // 领用方式,公斤 斤0,数量1
      } else {
        this.flagModal = false; // 如果规格不为公斤和斤默认显示数量(箱,件)
        // this.isFlagModal = false; // 用于判断选中规格后展示重量还是数量
        this.showForm.recipientsWay = 1; // 领用方式,公斤 斤0,数量1
      }
      this.isEdit = false;
    },
    // 添加出库量确认按钮
    onOk() {
      if (this.showForm.outWeight <= 0) {
        this.$Message.error("出库数量为零不让保存！");
        return;
      }
      if(this.showForm.outWeight > this.outboundWeight){
        this.$Message.error("出库数量大于库存数量,添加失败!");
        return;
      }
      if (this.flag === true && this.isEdit === false) {
        console.log("查看添加");
        this.postApiGoodsOutStockBillSavepooutstockbillApi();
      }
      if (this.flag === true && this.isEdit === true) {
        console.log("查看修改");
        this.postApiGoodsOutStockBillUpdatepooutstockbillApi();
      }
      if (this.flag === false && this.isEdit === false) {
        this.postApiGoodsOuthandaworkSaveApi();
        console.log("手工添加");
      }
      if (this.flag === false && this.isEdit === true) {
        this.updatePostOuthandaworkApi();
        console.log("手工编辑");
      }
    },
    // 模态框取消
    onCancel() {
      this.$refs["modal"].onCancel();
    },
    // 添加出库量规格事件
    modelChange(v) {
      if (v == "公斤" || v == "斤") {
        // this.isFlagModal = true; //按重量
        this.showForm.recipientsWay = 0;
      } else {
        // this.isFlagModal = false; //按数量
        this.showForm.recipientsWay = 1;
      }
    },
    // 手工出库物资登记-获取物资领用单--------------------接口
    postApiGoodsPoinventroyReceivepoinventroysApi() {
      this.form.loading = true;
      console.log(this.form.stockId);
      return new Promise((resolve) => {
        let params = {
          productName: this.form.productName,
          foodClassName: this.form.foodClassName,
          stockId: this.form.stockId,
          poinventroyType: 0,
          current: this.pages.page,
          size: this.pages.pageSize,
        };
        postApiGoodsPoinventroyReceivepoinventroys(params).then((res) => {
          this.form.loading = false;
          if (res.retCode == 2000) {
            this.data = res.data.records;
            this.pages.pageTotal = res.data.total;
          }
          resolve();
        });
      });
    },
    // 手工出库物资登记-获取物资食材种类-----------------接口
    productcategoryApi() {
      return new Promise((resolve) => {
        productcategory().then((res) => {
          if (res.retCode === 2000) {
            console.log('食材种类',res.data);
            this.productClassTree = res.data.records;
            resolve();
          }
        });
      });
    },
    // 获取规格数据-----------------------接口
    getGoodsSelectBasSpecificationListApi() {
      return new Promise((resolve) => {
        getGoodsSelectBasSpecificationList().then((res) => {
          if (res.retCode === 2000) {
            this.unitTree = res.data;
            console.log(this.unitTree);
            resolve();
          } else {
            this.$Message.error(res.retMsg);
          }
        });
      });
    },
    // 出库登记保存出库重量(手工添加)----------------接口
    postApiGoodsOuthandaworkSaveApi() {
      return new Promise((resolve) => {
        let params = {
          poinventroyId: this.showForm.id,
          productId: this.showForm.productId, // 商品id
          packagingPrice: this.showForm.packagingPrice, // 价格
          recipientsWay: this.showForm.recipientsWay, // 领用方式,公斤 斤0,数量1
          packagingQty: this.showForm.outWeight, // 出库量
          stockId: this.showForm.stockId, // 仓库id
        };
        postApiGoodsOuthandaworkSave(params).then((res) => {
          if (res.retCode == 2000) {
            this.$Message.success(res.retMsg);
            this.showModal = false;
            this.$parent.postApiGoodsOuthandaworkListApi();
            this.postApiGoodsPoinventroyReceivepoinventroysApi();
          }
          resolve();
        });
      });
    },
    // 出库登记保存出库重量(查看添加)----------------接口
    postApiGoodsOutStockBillSavepooutstockbillApi() {
      return new Promise((resolve) => {
        let params = {
          poinventroyId: this.showForm.id,
          productId: this.showForm.productId, //商品id
          billNo: this.caiGouBillNo, //采购单号
          packagingPrice: this.showForm.packagingPrice, //价格
          recipientsWay: this.showForm.recipientsWay, //领用方式,公斤 斤0,数量1
          packagingQty: this.showForm.outWeight, //出库量
        };
        postApiGoodsOutStockBillSavepooutstockbill(params).then((res) => {
          if (res.retCode == 2000) {
            this.$Message.success(res.retMsg);
            this.showModal = false;
            this.$parent.postApiGoodsOutStockBillGetApi();
            this.postApiGoodsPoinventroyReceivepoinventroysApi();
          } else {
            // this.$Message.error(res.retMsg)
          }
          resolve();
        });
      });
    },
    // 出库登记修改出库重量(查看修改)----------------接口
    postApiGoodsOutStockBillUpdatepooutstockbillApi() {
      return new Promise((resolve) => {
        let params = {
          id: this.showForm.id,
          packagingRealQty: this.showForm.outWeight,
        };
        postApiGoodsOutStockBillUpdatepooutstockbill(params).then((res) => {
          if (res.retCode == 2000) {
            this.$Message.success(res.retMsg);
            this.showModal = false;
            this.$parent.postApiGoodsOutStockBillGetApi();
          }
          resolve();
        });
      });
    },
    // 编辑出库量获取库存重量(修改后接口)-------------接口
    updateGoodsPoinventroyInfoApi() {
      return new Promise((resolve) => {
        updateGoodsPoinventroyInfo({
          id: this.showForm.poinventroyId, //物资id
        }).then((res) => {
          if (res.retCode == 2000) {
            if (res.data) {
              this.showForm.num = this.$cu.deepClone(res.data.num); //库存重量
              this.showForm.realQuantity = this.$cu.deepClone(
                res.data.realQuantity
              ); //已领用未登记重量
            }
          }
          resolve();
        });
      });
    },
    // 编辑出库量-------------接口
    updatePostOuthandaworkApi() {
      return new Promise((resolve) => {
        let params = {
          id: this.showForm.id,
          packagingRealQty: this.showForm.outWeight,
        };
        updatePostOuthandawork(params).then((res) => {
          if (res.retCode == 2000) {
            this.$Message.success(res.retMsg);
            this.showModal = false;
            this.$parent.postApiGoodsOuthandaworkListApi();
          }
          resolve();
        });
      });
    },
    // 物资仓库列表---------接口
    getBasstockListApi() {
      return new Promise((resolve) => {
        let params = {
          current: 1,
          size: 1000,
        };
        getBasstockList(params).then((res) => {
          console.log(res);
          if (res.retCode == 2000) {
            console.log('ddd',this.storehouseTree);
            this.storehouseTree = res.data.records;
            resolve();
          }
        });
      });
    },
  },
};
</script>

<style lang="less" scoped>
//物资表单 label-position="top"
.materials {
  /deep/.ivu-form-item-label {
    display: flex;
    justify-content: flex-start !important;
  }
}
</style>
